package top.yongyan0624.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import top.yongyan0624.entity.Answer;
import top.yongyan0624.entity.Question;
import top.yongyan0624.mapper.QuestionMapper;
import top.yongyan0624.service.AnswerService;
import top.yongyan0624.service.QuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yongyan
 * @since 2021-05-22
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private AnswerService answerService;

    @Override
    public Question question() {
        //获取所有question
        List<Question> questionList = this.list();
        //随机选出一个question
        int index = RandomUtil.randomInt(questionList.size());
        Question question = questionList.get(index);
        //根据question的id，选出它对应的所有选项以及一个正确选项，将内容转成数组
        List<Answer> answerList = answerService.list(new QueryWrapper<Answer>().eq("question_id", question.getId()));
        Answer rightAnswer = answerService.getOne(new QueryWrapper<Answer>().eq("id", question.getRight()));
        String[] answers = answerList.stream().map(Answer::getContent).toArray(String[]::new);
        //将正确答案的数组下标写入
        for (int i = 0; i < answers.length; i++) {
            if (answers[i].equals(rightAnswer.getContent())){
                question.setRight((long) i);
                break;
            }
        }
        question.setAnswer(answers);

        return question;
    }
}
